﻿var rate = $.cookie("GemRate") || 1;
var gem;
var orderID;
var scrollToph;
var  notbtn=""; //1有按钮
var app_url=location.origin;
var curstate = 0; //当前类别选项
var datalist = {};
    

(function(){
	OrderSearch();
	var order={
		init:function(){
			//导航栏的选中
            $('.wrapper').navbarscroll();
            $("#categories li").eq(2).addClass("cur").siblings().removeClass("cur");
			this.BindEvents();
		},
		BindEvents:function(){
			var self = this;
			if(APP){
				$("#order_term_btn").remove();
			}
            //筛选
            $("#order_term_btn").on("click", function () {
                if(APP){
                	var appJson={};
            		appJson.title=_("订单筛选");
            		appJson.url=app_url+"/Team/OrderFilter/?type=4";
            		YiYi_APP.showNewPage(JSON.stringify(appJson));
                }else{
                	location.href="/Team/OrderFilter/?type=4";
                }
            });
            $(".order-status span").on("click", function () { //订单状态选中
                $(this).addClass("active").siblings().removeClass("active");
            });
            //其他筛选条件点击添加样式、可多选
            $("#order_term_box").on("click", ".term span", function () {
                $(this).toggleClass("active");
            });
            $("#filter_product_btn").on("click", function () {
                $("#common_header").show();
                $("#order_term_btn").show();
                $("#order_term_box").hide();
                OrderSearch();
            });
			//点击全选
			$("#checkbox_check_all").on("click",function(){
				self.countCheck(0,0,0);//取消
				$(this).toggleClass("selected")
				if($(this).hasClass("selected")){
					$("#order .check_list_box").children("span").addClass("selected");
					$("#order .check_list_box span.selected").each(function (i, item) {
						var pre = parseFloat($(item).closest("li").find(".first").text());//当前点击行的每卡
    					var totalprice = parseFloat($(item).closest("li").find(".CurrentRMB .product_list_price").text());
    					var usd_totalprice = parseFloat($(item).closest("li").find(".CurrentUSD .product_list_price").text());
    					handleBtn();
						self.countCheck(1,pre,totalprice);
						self.countCheck(1,pre,usd_totalprice,"usd");
					});		
				}else{
					$(".check_list_box").children("span").removeClass("selected");
					clearAll();
					self.countCheck(0,0,0);//取消
				}
			});
			//列表的勾选框
			$("#order").on("click",".check_list_box",function(){
				$(this).children("span").toggleClass("selected");
				var pre = parseFloat($(this).closest("li").find(".first").text());//当前点击行的每卡
                var totalprice = parseFloat($(this).closest("li").find(".CurrentRMB .product_list_price_rmb").attr('data-PurchaseRMB'));
                var usd_totalprice = parseFloat($(this).closest("li").find(".CurrentUSD .product_list_price_usd").attr('data-PurchaseUSD'));
				//判断是否全选
				var length=$("#order .check_list_box span.checkbox").length;
				var checkLength=$("#order .check_list_box span.selected").length;
				if(checkLength>0){
					handleBtn();
				}else{
					clearAll();
				}
				
				if(length==checkLength){
					$("#checkbox_check_all").addClass("selected");
				}else{
					$("#checkbox_check_all").removeClass("selected");
				}				
				if($(this).children("span").hasClass("selected")){
					self.countCheck(1,pre,totalprice);//选中
					self.countCheck(1,pre,usd_totalprice,"usd");//选中
				}else{
					self.countCheck(2,pre,totalprice);//取消
					self.countCheck(2,pre,usd_totalprice,"usd");//取消
				}
				
			});
			
			//采购订单输入验证 class=purchase_form
            var validate = $(".purchase_form").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form   
                    PurchaseOrder();//采购订单
                },
                rules: {
                    OriginSN:"required", 
                    Category:"required", 
                    Shape:"required", 
                    Color: "required", 
                    CertType: "required", 
                    CertNo: "required", 
                    Weight: "required", 
                    Place: "required",
                    ConfirmPrice: "required",
                    PurchaseRemarks:"required",
                },
                messages: {
                    MainColor:"", 
                    OriginSN:"", 
                    Category:"", 
                    Shape:"", 
                    Color: "", 
                    CertType: "", 
                    CertNo: "", 
                    Weight: "", 
                    Place: "",
                    ConfirmPrice: "",
                    PurchaseRemarks:"",
                    
                }
            });

			//回裸钻库输入验证 class=_backdia
            var validate = $("._backdia").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form   
                    BackDia();//添加裸钻(回裸钻库)
                },
                rules: {                    
                    OriginSN: "required",
                    Weight: "required", 
                    Shape: "required", 
                    Color:"required",  
                    Cut: "required", 
                    DeliveryTime:"required", 
                    Supplier:"required", 
                    CertNo:"required", 
                    CertType:"required",
                    PriceUSD: "required",  
                    Place: "required",
                    
                },
                messages: {
                    OriginSN:"",                
                    Weight:"",
                    Shape:"",
                    Color: "",
                    Cut:"",
                    DeliveryTime:"",
                    Supplier: "",
                    CertNo:"",
                    CertType:"required",
                    PriceUSD:"",
                    Place:"",
                }
            });

		},

        //统计数据
        countCheck:function(type,pre,totalPrice,usd){			
			var price=parseFloat($("#check-total-price").text());
			var usd_price=parseFloat($("#check-total-price-usd").text());
			var pre_price=parseFloat($("#check-m-rmb").text());
			var _num = $(".check_list_box span.selected").length;;	
			if(type==1){//加				
				if(usd=="usd"){
					usd_price+=totalPrice
				}else{
					price+=totalPrice
					pre_price+=pre
				}
			}
			if(type==2){//减
				
				if(usd=="usd"){
					usd_price-=totalPrice
				}else{
					price-=totalPrice
					pre_price-=pre
				}
			}
			if(type==0){
				_num=0;
				price=0;
				usd_price=0;
				pre_price=0;
			}
			$("#check-num").text(_num);
			$("#check-m-rmb").text(formatRMBPrice(pre_price));
			$("#check-total-price").text(formatRMBPrice(price));
			$("#check-total-price-usd").text(formatUSDPrice(usd_price));
		},

		
	}
	order.init();
})();
 

//处理
function GetProcess(data){
	var type=data.Category;
	if(type==1 || type==2){
		 return	"<b class='process'>"+GetText("gems",type,data.Process,"Process")+"</b>";
	}
	return "";
}
//油性
function GetOiliness(data){
	var type=data.Category;
	if(type==3){
		 return	"<b class='oiliness'>"+GetText("gems",type,data.Oiliness,"Oiliness")+"</b>";
	}
	return "";
}
        
        //绑定数据
        function BindingOrder(result) {
        	
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if (_result.msgcode == false) {//获取库存失败
                 $("#order_list").html('<div style="text-align:center;padding-top:20px;width:100%;">'+_(_result.msginfo)+'</div>');
            } else { //获取库存成功
                _result = _result.msginfo;
                var lis = "";//多行数据
                for (var i = 0; i < _result.length ; i++) {//_result.length
					var li = ""; //单行
					var data = _result[i];
                    var data_parse=JSON.parse(data.InventoryAttribute);

                    lis += "<li>"+
                    "<div>"+
                    "<div class='check_list_box' lang='"+data.ReceiptStatus+"' data-customerID='"+data.CustomerID+"'>"+
                    "<span class='checkbox' name='checkbox' lang='" + data.OrderID + "' data='"+data.OrderStatus+"'></span></div>"+
                    "<div class='product_list' data-id="+data.OrderID +">"+
                    "<label class='product-parameter' data='"+data.Remarks+"' data-id='"+data.OrderID+"'  data-sn='"+data.OriginSN+"' data-pay='"+data.ReceiptStatus+"' lang='"+data.SalesExchangerate+"' style='display:none'></label>"+
                    "<div class='list_img_box'>"+ShowImgOne(data_parse)+"</div>"+
					"<div class='list_detail_box'>"+
					"<p>"+					
					"<b class='category' data='"+data_parse.Category+"'>" + GetCategory("gems",data_parse.Category) + "</b><b title='货号'>"+data_parse.OriginSN+"</b>" +
					"<b class='shape' data='" + data_parse.Shape + "'>" + GetText("gems",data_parse.Category,data_parse.Shape,"Shape") + "</b>" +
					"<b class='certType'>" + GetText("gems",data_parse.Category,data_parse.CertType,"CertType") + "</b><b class='certNo'>" + data_parse.CertNo + "</b>" +
                    "<b class='measurement'>" + data_parse.Measurement + "</b><b class='color'>" + GetText("gems",data_parse.Category,data_parse.Color,"Color") + "</b>" +GetProcess(data)+GetOiliness(data)+
                    "<b class='weight'>" + data_parse.Weight + "</b><b class='cut'>" + data_parse.Cut + "</b><b class='cutMethod'>" + GetText("gems",data_parse.Category,data_parse.CutMethod,"CutMethod") + "</b>"+
                    "<b class='place'>" + GetText("gems",data_parse.Category,data_parse.Place,"Place") + "</b></p>"+
					"<div class='list_price' lang='"+formatRMBPrice(data.PriceCarat)+"'>"+
						"<span class='CurrentRMB'>￥<b class='product_list_price_rmb' data-PurchaseRMB='"+data.PurchaseRMB+"'>" + formatRMBPrice(data.ConfirmRMB) +"</b></span>"+
						"<span class='CurrentUSD'>$<b class='product_list_price_usd'  data-PurchaseUSD='"+data.PurchaseUSD+"'>" + formatUSDPrice(data.ConfirmUSD) +"</b></span>"+
					"</span><span class='status_box' style='margin-left:10px'>"+ReceiptStatusFormat(data.ReceiptStatus)+"</span><span class='status_box' lang='"+data.OrderStatus+"'>"+UserOrderStatusFormat(data.OrderStatus)+"</span></div>"+
					"<div class='time_box'>"+_("下单日期")+"：<span class='order-time'>"+DateTimeFormat(data.CreateTime)+"</span></div>"+
					"</div></div>"+
					"</div></div>"+modify_boxsGems(data)+
					"</li>";

					lis += li;//将单行加到多行
                }
                $("#order_list").html(lis);
                currentShow();  //币种设置
                //   @*主题色start*@
			    $(document.createElement("script")).attr("src","/Js/ThemesColor.js").appendTo("html");
				//  @*主题色end*@
            }
        }
        
   
//自留回库 12-15 
function BackDia_Js(me,gwRate) {
	categoryTypeShow(me);

    $.ajax({
        url: "/Team/GetOrderNew",//提交地址
        type: "POST",//提交方式
        data: "{'OrderID':'" + me.getAttribute("value") + "'}",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if(_result.msgcode==true){
            _result = _result.msginfo;
             var data_parse=JSON.parse(data.InventoryAttribute)
            myApp.popup(".BackDia_box");

            $("#_orID").val(_result.OrderID);//12-16
            $("#_invID").val(_result.ID);
            $("#originSN").val(data_parse.OriginSN);
            $("#category").val(data_parse.Category);
            $("#shape").val(data_parse.Shape);
            $("#color").val(data_parse.Color);
            $("#certType").val(data_parse.CertType);
            $("#certNo").val(data_parse.CertNo);
            $("#cut").val(data_parse.Cut);
            $("#cutMethod").val(data_parse.CutMethod);
            $("#weight").val(data_parse.Weight);
            $("#measurement").val(data_parse.Measurement);
            $("#supplier").val(data_parse.Supplier);
            $("#place").val(data_parse.Place);
            $("#isStock").val(data_parse.IsStock);
            $("#oiliness").val(data_parse.Oiliness);
            $("#process").val(data_parse.Process);
            
            $("#remark").val(data_parse.Remark);
            $("#onShelves").val(data_parse.OnShelves);

//          //原采购部分 01-12
            $("#back_purchaseExchange").val(_result.PurchaseExchangerate);//01-12采购汇率
            $("#sourceRMBGrain").val(Math.round(_result.PurchaseRMB)); //原人民币
            var back_purchaseRMBperCarat =Math.round((_result.PurchaseRMB / parseFloat($("#back_purchaseExchange").val())) / _result.Weight);
            $("#back_purchaseRMBperCarat").val((Math.round(_result.PurchaseRMB / _result.Weight))); //采购人民币每卡
            $("#sourceUSDPerGrain").val(Math.round(_result.PurchaseRMB / parseFloat($("#back_purchaseExchange").val())));//原美金
            $("#back_purchaseUSDPerCarat").val(Math.round(_result.PurchaseRMB / parseFloat($("#back_purchaseExchange").val()) / _result.Weight));//01-12  carat/usd采购美金每卡
        
//          //买
//          $("#buyUSDPerGrain").val(_result.PriceUSD);//01-12 买美金
//          $("#buyRMBGrain").val((_result.ConfirmPrice / (100 + _result.Confirmdiscount) * (100 + _result.DiscountReturn)).toFixed(2));//01-12买RMB

 			}else{
                $(".BackDia_box").hide();
                toast(_result.msginfo);     	
           	}

        }
    });
}    
        //回裸钻库12-16
        function BackDia(me){
            var requestDia = {};

            requestDia.OrderID = $("#_orID").val();//12-16
            requestDia.ID = $("#_invID").val();

            requestDia.OriginSN = $("#originSN").val();
            requestDia.Category = $("#category").val();
            requestDia.Shape = $("#shape").val();
            requestDia.Color = $("#color").val(); 
            requestDia.CertType = $("#certType").val();
            requestDia.CertNo = $("#certNo").val();
            requestDia.Cut = $("#cut").val();
            requestDia.CutMethod = $("#cutMethod").val();
            requestDia.Weight = $("#weight").val();
            requestDia.Measurement = $("#measurement").val();
            requestDia.Supplier = $("#supplier").val();  
            requestDia.Place = $("#place").val();
 			requestDia.IsStock = $("#isStock").val();  
            requestDia.Oiliness = $("#oiliness").val();            
            requestDia.Process = $("#process").val();
            requestDia.OnShelves = $("#onShelves").val();//上下架 12-28            
            requestDia.Comments = $("#remark").val();

//          原采购
			requestDia.PurchaseExchangerate = $("#back_purchaseExchange").val();//原采购汇率
//			requestDia.PurchaseRMBperCarat = $("#back_purchaseRMBperCarat").val();//原采购每卡￥
//			requestDia.PurchaseUSDPerCarat = (parseFloat($("#back_purchaseRMBperCarat").val()) / parseFloat($("#back_purchaseExchange").val())).toFixed(2); //$("#back_purchaseUSDPerCarat").val();//原采购每卡$
			requestDia.ConfirmPrice = (parseFloat($("#back_purchaseRMBperCarat").val()) *  parseFloat($("#weight").val())).toFixed(1); // $("#sourceRMBGrain").val(); //原采购总价￥
            requestDia.PurchaseUSDPerGrain = (parseFloat($("#back_purchaseRMBperCarat").val()) *  parseFloat($("#weight").val()) * parseFloat($("#back_purchaseExchange").val())).toFixed(2);   //$("#back_purchaseUSDPerGrain").val();//原采购总价$
            

//          //买
			requestDia.BuyUSDPerGrain = $("#buyUSDPerGrain").val();//买美金
			requestDia.BuyRMBGrain = $("#buyRMBGrain").val();//买人民币

            

            $.ajax({
                url: "/Team/GemstockOrders",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(requestDia),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象

                    if (_result.msgcode == false) {
                        //添加失败(接口错误或程序内部错误)
                        myApp.alert(_("新增失败")+"：" + _(_result.msginfo));
                    } else {
                        //添加成功
                        if (_result.result == true) {
                            //{\"count\": 1, \"ids_insert\": [5158997], \"ids\": [5158997], \"ids_update\": [], \"result\": true, \"count_update\": 0, \"count_insert\": 1}
                            myApp.alert(_("成功条目")+"：" + _result.count + _("\n\n新增条目")+"：" + _result.count_insert + _("\n\n更新条目")+"：" + _result.count_update);
                            myApp.closeModal(".BackDia_box");//回库框关闭
                            OrderSearch();
                        } else {
                            //请求参数不符{\"msg\": \"\\u4ef7\\u683c\\u8f6c\\u6362\\u5931\\u8d25\", \"result\": false}
                            myApp.alert(_("新增失败")+"：" + _(_result.msg));
                        }
                    }
                }
            });
        }
        //修改订单
        function modify_box(me) {
			categoryTypeShow(me);
			currentPurShow(); //采购的币种设置
            $.ajax({
                url: "/Team/GetOrderNew",//提交地址
                type: "POST",//提交方式
                data: "{'OrderID':'" + me.getAttribute("value") + "','GoodsType':'"+4+"'}",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                	if(_result.msgcode==true){
	                _result = _result.msginfo;
	                var data_parse=JSON.parse(_result.InventoryAttribute)
	                myApp.popup(".modify_pop_box");
            
	            	$("#_orderID").val(_result.OrderID);
                    $("#_orderStat").val(_result.OrderStatus);//隐藏域11-3 
                    $("#_purOriginSN").val(data_parse.OriginSN);
                    $("#_purCategory").val(data_parse.Category);
                    $("#_purShape").val(data_parse.Shape);
                    $("#_purColor").val(data_parse.Color);
                    $("#_purCertType").val(data_parse.CertType);//证书类型
                    $("#_purCertNo").val(data_parse.CertNo);
                    $("#_purProcess").val(data_parse.Process);
		            $("#_purCut").val(data_parse.Cut);
		            $("#_purCutMethod").val(data_parse.CutMethod);
		            $("#_purOiliness").val(data_parse.Oiliness);
		            $("#_purWeight").val(data_parse.Weight);
		            $("#_purMeasurement").val(data_parse.Measurement);
		            $("#_purSupplier").val(data_parse.Supplier);
		            $("#_purPlace").val(data_parse.Place);
		            $("#_purConfirmPrice").val(_result.ConfirmPrice);
		            // $("#_purIsStock").val(_result.IsStock);
		              
                    $("#_purchaseExchange").val(_result.PurchaseExchangerate);  
                    $("#_PurchaseRemarks").val(_result.Remarks);
                    // $("#_deliveryTime").val(DateTimeFormat(_result.ShipTime));
                    $("#_buyPriceUSD").val(formatUSDPrice(parseFloat(_result.PurchaseUSD))); //买美金
                    $("#_buyPrice").val(formatRMBPrice(parseFloat(_result.PurchaseRMB))); //买人民币
	            }else{
	                $(".modify_pop_box").hide();
	                toast(_(_result.msginfo));
	            }
                    
                }
            });
        }
        
  		//采购订单8-20
        function PurchaseOrder(me) {  

            var requestOrder = {};
		
            requestOrder.OrderID = $("#_orderID").val();
            requestOrder.OrderStatus = $("#_orderStat").val();//11-3
            requestOrder.OriginSN = $("#_purOriginSN").val();//货号
            requestOrder.Category =$("#_purCategory").val();
            requestOrder.Shape =$("#_purShape").val();
            requestOrder.Color =$("#_purColor").val();
            requestOrder.CertType =$("#_purCertType").val();
            requestOrder.CertNo =$("#_purCertNo").val();
            requestOrder.Process =$("#_purProcess").val();
            requestOrder.Cut =$("#_purCut").val();
            requestOrder.CutMethod =$("#_purCutMethod").val();
            requestOrder.Oiliness =$("#_purOiliness").val();
            requestOrder.Weight = $("#_purWeight").val();
            requestOrder.Measurement =$("#_purMeasurement").val();
            requestOrder.Supplier =$("#_purSupplier").val();
            requestOrder.Place =$("#_purPlace").val();
            requestOrder.PurchaseRemarks = $("#_PurchasesRemarks").val();
            requestOrder.PurchaseExchangerate = $("#_purchaseExchange").val(); //采购汇率
            requestOrder.PurchaseRMB =  $("#_buyPrice").val();//买RMB
            requestOrder.PriceUSD = $("#_buyPriceUSD").val();;//买美金
            

            $.ajax({
                url: "/team/PurchaseOrderNew",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(requestOrder),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
					myApp.alert(_(_result.msginfo));
                    myApp.closeModal(".modify_pop_box");//关闭采购订单框8-28
                    OrderSearch();//搜索订单8-28  
                }
            });
        }
        

		function categoryTypeShow(type){
			var type = $(type).attr("lang");
  
			//产地		
			var place = "";
			$(".place option").remove();
			if(type != 0){
	        for(var i=0;i<gem[type].Place.length;i++){
	            place += '<option value="'+gem[type].Place[i][0]+'">'+_(gem[type].Place[i][1])+'</option>';
	        	}
	       }
	       $("#_purPlace").html(place);
	        //颜色
	        var color = "";
	        $(".color option").remove();
	        if(type != 0){
	        for(var i=0;i<gem[type].Color.length;i++){
	             color += '<option value="'+gem[type].Color[i][0]+'">'+_(gem[type].Color[i][1])+'</option>';
	            }
	        }
	        $("#_purColor").html(color);

	        // $(".place select").append(place);
           	// $(".place").show();
//         	祖母绿
			if(type==3){
				$(".oiliness").show();
			}else{
				$(".oiliness").hide();
			}
	        //红宝和蓝宝
            if(type==1 || type==2){
       		//处理
           		$(".process").show();
            }else{
            	$(".process").hide();
            }



			
		}
       
        
   
